package com.example.dqreptile.utils;


import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import org.openqa.selenium.remote.RemoteWebDriver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class MyChromeDriver {

    @Value("${webdriver.driverPath}")
    private String driverPath;

    @Value("${webdriver.driver}")
    private String driver;

    private static int count = 0;

    private static List<WebDriver> webDriverList = new ArrayList<>();

    private static List<WebDriver> webDrivers =  Collections.synchronizedList(webDriverList);

    public ChromeDriver getLocalChromeDriver() {


        System.setProperty(driver, driverPath);
        ChromeDriver browser = new ChromeDriver();
        browser.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        return new ChromeDriver();
    }

    /**
     * 初始化大小
     */
     public void listSize(int count){

         for (int i = 0; i < count; i++) {
             try {
                 webDrivers.add(getRemoteChromeDriver());
             } catch (MalformedURLException e) {
                 e.printStackTrace();
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
     }

    /**
     * 远程 ChromeDriver
     *
     * @return
     * @throws MalformedURLException
     * @throws InterruptedException
     */
    public WebDriver getRemoteChromeDriver() throws MalformedURLException, InterruptedException {

        WebDriver driver = new RemoteWebDriver(new URL("http://192.168.170.129:4444/wd/hub"), new ChromeOptions());
        driver.manage().timeouts().implicitlyWait(10
                , TimeUnit.SECONDS);
        driver.manage().window().maximize();
        return driver;
    }


    /**
     * 获取驱动
     *
     * @return
     */
    public synchronized WebDriver getOnlineDriver() {
        System.out.println(webDrivers.size());

        if (webDrivers.size() > 0) {
            WebDriver webDriver = webDrivers.get(0);
            webDrivers.remove(webDriver);
            return webDriver;
        }

        if (count > 6) {
            return null;
        }
        try {
            webDrivers.add(getRemoteChromeDriver());
            count++;
            return webDrivers.get(0);
        } catch (MalformedURLException e) {
            log.error("创建webDrivers时报错！错误{}", e.getMessage());
            // e.printStackTrace();
        } catch (InterruptedException e) {
            log.error("创建webDrivers时报错！错误{}", e.getMessage());
            //e.printStackTrace();
        }
        return null;
    }


}
